/**
 *  *2010-5-28 下午12:21:56  add 
 */
package com.base.myproject.client.ui;

import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BaseStoreEvent;
import com.base.myproject.client.busi.BaseStoreListener;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncGetModelDatas;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.store.StoreFilter;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * 多选界面
 * @author Administrator
 *2010-5-28
 * javazgw@gmail.com
 */
public class MutilItemPanel extends LayoutContainer implements BaseStoreListener{

	BaseStore<BusiObject> sourcestore = new BaseStore<BusiObject>();
	BaseStore<BusiObject> tarstore =new BaseStore<BusiObject>();
//	StoreInfo sourceinfo;
	StoreInfo tarinfo;
//	ColumnModel sourcecm ;
//	ColumnModel tarcm ;
	List<ColumnConfig> sourcecolumns;
	List<ColumnConfig> tarcolumns;
	BaseGrid<BusiObject> sourcegrid;
	BaseGrid<BusiObject> targrid;
	String[] copycolumn;
	String sqlname;//sqltable 里设定的sql名称
	Button add = new Button("添加");
	Button del = new Button("移除");
	ModelType type ;
	public MutilItemPanel(List<ColumnConfig> sourcecolumns,List<ColumnConfig> tarcolumns,StoreInfo tarinfo,String sqlname,String[] copycolumn,ModelType type )
	{
		this.sourcecolumns = sourcecolumns;
		this.tarcolumns = tarcolumns;
		this.tarinfo = tarinfo;
		this.sqlname = sqlname;
		tarstore.setStoreinfo(tarinfo);
		tarstore.setType(type);
		this.copycolumn = copycolumn;
		this.type =type;
		init();
		createSourceStore();
		tarstore.initcompleted();
		if(tarinfo.getParent()!=null)
		{
			tarstore.addBaseStoreListener(BaseStoreEvent.EventType.LOAD_COMPLETE, this);
		}
		
	}

	private void init() {
		add.addListener(Events.Select, getListener());
		del.addListener(Events.Select, getListener());
		initwidget();
		
	}

	private void initwidget() {
		VerticalPanel v = new VerticalPanel();
		HorizontalPanel h = new HorizontalPanel();
		h.setVerticalAlign(VerticalAlignment.MIDDLE);
		h.add(add);
		h.add(del);
		
		FieldSet fs1 = new FieldSet();
		fs1.setHeading("请选择数据");
		fs1.add(createSourceGrid());
		
		FieldSet fs2= new FieldSet();
		fs2.setHeading("已经添加数据");
		fs2.add(createTarGrid());
		v.add(fs1);
		v.add(h);
		v.add(fs2);
		
//		v.setAutoWidth(true);
//		v.setWidth(500);
		this.add(v);
	}

	BaseGrid<BusiObject> createSourceGrid() {
		CheckBoxSelectionModel<BusiObject> cbs = new CheckBoxSelectionModel<BusiObject>();
		
		sourcecolumns.add(0,cbs.getColumn());
		
		ColumnModel sourcecm = new ColumnModel(sourcecolumns);
		sourcegrid = new BaseGrid<BusiObject>(sourcestore, sourcecm, false,
				false);
		cbs.setSelectionMode(SelectionMode.MULTI);
		sourcegrid.setSelectionModel(cbs);
		sourcegrid.setHeight(200);
		sourcegrid.setWidth(300);
		sourcegrid.getView().setForceFit(true);
		return sourcegrid;
	}
	
	BaseGrid<BusiObject> createTarGrid() {
		CheckBoxSelectionModel<BusiObject> cbs = new CheckBoxSelectionModel<BusiObject>();
		
		tarcolumns.add(0,cbs.getColumn());
		
		ColumnModel tarcm = new ColumnModel(tarcolumns);
		targrid = new BaseGrid<BusiObject>(tarstore, tarcm, true,true);
		cbs.setSelectionMode(SelectionMode.SINGLE);
		targrid.setSelectionModel(cbs);
		targrid.setHeight(200);
		targrid.getView().setForceFit(true);
		return targrid;
	}
	
	
	
	void createSourceStore()
	{
		CommandSyncContainer list = new CommandSyncContainer();

		CommandSyncGetModelDatas csgmd = new CommandSyncGetModelDatas();
		csgmd.setSqlname(sqlname);
//		csgmd.putmacro("SCARDNO", s_cardno.getValue());
		list.add(csgmd);
		final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService
				.SendCommandSync(
						list,
						new AsyncCallback<CommandSyncReturnObject>() {

							@Override
							public void onFailure(
									Throwable caught) {
								MessageBox.alert("错误",
										"网络连接失败", null);

							}

							@Override
							public void onSuccess(
									CommandSyncReturnObject result) {
								if (result.isB()) {
									// BaseStore<BusiObject>
									// salarystore = new
									// BaseStore<BusiObject>();
									if (result
											.getCommandsync() instanceof CommandSyncGetModelDatas) {
										// salarystore.add(((CommandSyncGetModelDatas)(result.getCommandsync())).getList(),false);
										// System.out.println(salarystore.getCount());
										//System.out.println(((CommandSyncGetModelDatas)(result.getCommandsync())).getList());
									
										sourcestore.removeAll();
										sourcestore.add(((CommandSyncGetModelDatas)(result.getCommandsync())).getList(),false);
										
										
										
									}

								} else {
									MessageBox
											.alert(
													"错误",
													""
															+ result
																	.getMessage(),
													null);

								}

							}

						});
	}
	
	int sync = 0;
	Listener<BaseEvent> defaultlistener;

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.Select) {
							 if (be.getSource().equals(add)) {
								 
								 for(BusiObject bo:sourcegrid.getSelectionModel().getSelectedItems())
								 {
									 
									 BusiObject botemp = new BusiObject();
									
									 for(String  cc :copycolumn)
									 {
										 botemp.set(cc,bo.get(cc));
										 
									 }
									 if(tarinfo.getParent()!=null)
									 {
										 if(tarinfo.getLinkparentcolumns()!=null)
											 for(int i=0;i<tarinfo.getLinkparentcolumns().length;i++)
										 {
											 botemp.set(tarinfo.getLinkparent_chile_columns()[i], tarinfo.getParent().getValue(tarinfo.getLinkparentcolumns()[i]));
										 }
									 }
									// if(!tarstore.contains(botemp))
										 tarstore.add(botemp,false,false);
								 }
								 filter();
//								 sourcestore.filter(property)
//								 tarstore.add( sourcegrid.getSelectionModel().getSelectedItems(),false);
							 }
					
						} else if (be.getType() == Events.Change) {
							
//							if (be.getSource().equals(s_cardno)) {
//								
//								
//							}
//							
//							else if (be.getSource().equals(finace)) {
//								
//							}
						} else if (be.getType() == Events.KeyUp) {
//							if (be instanceof ComponentEvent) {
//								if (((ComponentEvent) be).getKeyCode() == 13) // 回车
//								{
//								}
//							}
//							if (be.getSource().equals(finace))
//							{
//								
//								
//							}
							
							
						}
					}
				} finally {
					sync--;
				}
			}

		};
		return defaultlistener;
	}
	/**
	 * 过滤，过滤目的表存在则过滤源表
	 */
	public void filter()
	{
		 sourcestore.clearFilters();
		 sourcestore.addFilter(filter);
		 sourcestore.applyFilters("");
	}
	/**
	 * 过滤条件，目的表存在则过滤源表
	 */
	StoreFilter<BusiObject> filter = new StoreFilter<BusiObject>(){

		@Override
		public boolean select(Store<BusiObject> store, BusiObject parent,
				BusiObject item, String property) {
			
		
			for(int i=0;i<tarstore.getCount();i++)
			{
//				for(int j=0;j<sourcestore.getCount();j++)
//				{
				boolean b=false;
					 for(int k=0;k<copycolumn.length;k++)
					 {
					
						
					
						 if((tarstore.getValue(i, copycolumn[k])==null || item.get(copycolumn[k])==null))
						 {
							 b=false;
							 break;
						 }
						 if (!(tarstore.getValue(i, copycolumn[k]).equals(item.get(copycolumn[k]))))
						 {
							
							 b=false;
							 break;

						 }
						 else
						 {
							b=true;
						 }
						 
					 }
					 if(b)
						 return false;
					
//				}
			}
			return true;
		}
		
	};
	
	
	/*{
		@Override
		protected boolean doSelect(Store<BusiObject> store,
				BusiObject parent, BusiObject record, String property,
				String filter) {
//			for (int i = 0; i < type.getFieldCount(); i++) {
//
//				Object name = record.get(type.getField(i).getName());
//				
//				//TODO
//				if (name!=null&&name.toString().indexOf(filter.toLowerCase()) != -1) {
//					return true;
//				}
				
				
//			}
			
			for(int i=0;i<tarstore.getCount();i++)
			{
				for(int j=0;j<sourcestore.getCount();j++)
				{
					 for(ColumnConfig cc :tarcolumns)
					 {
						 if(!tarstore.getValue(i, cc.getId()).equals(sourcestore.getValue(j,cc.getId())))
						 {
							 return false;
						 }
						 
					 }
					
				}
			}
			return true;
		//return	Select(store,parent,record,property,filter);
		}

		@Override
		protected void onFilter() {
			super.onFilter();

			// grid.getSelectionModel().select(0);
		}

	};*/
	
	public void BaseStoreEventHandle(BaseStoreEvent evt) {
		if(evt.getEventType()==BaseStoreEvent.EventType.LOAD_COMPLETE)
		{
			filter();
		}
		
	}

	public BaseGrid<BusiObject> getSourcegrid() {
		return sourcegrid;
	}

	public void setSourcegrid(BaseGrid<BusiObject> sourcegrid) {
		this.sourcegrid = sourcegrid;
	}

	public BaseGrid<BusiObject> getTargrid() {
		return targrid;
	}

	public void setTargrid(BaseGrid<BusiObject> targrid) {
		this.targrid = targrid;
	}
	
	
}
